/**
 * Copyright (C) 2025 pony working team
 * SPDX-License-Identifier: MulanPSL-2.0
 */

/* define to prevent recursive inclusion -------------------------------------*/
#ifndef __M_MEMPOOL_H__
#define __M_MEMPOOL_H__

/* includes (standard library, system) ---------------------------------------*/
#include <stdint.h>
/* includes (other library) --------------------------------------------------*/
/* includes (project) --------------------------------------------------------*/
#include <x_module.h>
#include <x_list.h>

#include <k_sem.h>
#include <k_mutex.h>
#include <k_errno.h>
#include <k_obj.h>
/* includes (local) ----------------------------------------------------------*/

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/* defines -------------------------------------------------------------------*/

#define ERRNO_MEMPOOL_ILLEGAL_ID        ERRNO_JOIN(MID_MEMPOOL, 1)
#define ERRNO_MEMPOOL_ILLEGAL_PARA      ERRNO_JOIN(MID_MEMPOOL, 2)
#define ERRNO_MEMPOOL_ILLEGAL_OPERATION ERRNO_JOIN(MID_MEMPOOL, 3)
#define ERRNO_MEMPOOL_BUSY              ERRNO_JOIN(MID_MEMPOOL, 4)

/* typedefs ------------------------------------------------------------------*/

typedef struct mempool {
    obj_t obj;
    size_t item_size;
    size_t nr_items;
    sem_t sem;
    mutex_t lock;
    dlist_t items;
    char *buf;
} mempool_t, *mempool_id;

/* macro ---------------------------------------------------------------------*/
/* inlines -------------------------------------------------------------------*/
/* externs -------------------------------------------------------------------*/

extern mempool_id mempool_create(size_t size, size_t items, char *buf);
extern int mempool_destroy(mempool_id pool);
extern char *mempool_alloc(mempool_id pool);
extern int mempool_free(mempool_id pool, char *item);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __M_MEMPOOL_H__ */
